﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Core.Configuration;
using Caliburn.Core.InversionOfControl;
using Caliburn.MEF;
using Caliburn.PresentationFramework;
using Caliburn.PresentationFramework.ApplicationModel;
using Caliburn.PresentationFramework.Configuration;
using Caliburn.PresentationFramework.Conventions;
using Caliburn.PresentationFramework.RoutedMessaging;
using Caliburn.ShellFramework;
using Caliburn.ShellFramework.Results;
using MTGenome.ViewModels;

namespace MTGenome
{
    [Singleton(typeof(IRescueApp)), PartCreationPolicy(CreationPolicy.Shared)]
    public sealed class Bootstrapper : Bootstrapper<MainWindowViewModel>, IRescueApp
    {
        private static readonly Assembly _mtgenomeAssembly = Assembly.Load("MTGenome.Gatherer");

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            foreach (var item in base.SelectAssemblies())
            {
                yield return item;
            }

            yield return _mtgenomeAssembly;
        }

        protected override IServiceLocator CreateContainer()
        {
            var container = new CompositionContainer(new AssemblyCatalog(_mtgenomeAssembly));

            return new MEFAdapter(container);
        }

        protected override void Configure(IConfigurationBuilder builder)
        {
            builder.With
                .PresentationFramework()
                .RegisterAllItemsWithSubjects()
                .Using(x => x.ConventionManager<DefaultConventionManager>());

            base.Configure(builder);
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            //Want to turn off proxy for now, we'll figure out a cleaner method
            //This speeds up the first request to gatherer
            System.Net.WebRequest.DefaultWebProxy = null;

            base.OnStartup(sender, e);
        }

        protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;

            base.OnUnhandledException(sender, e);

            Rescue(e.Exception);
        }

        public void Rescue(Exception exc)
        {
            Clipboard.SetData(DataFormats.Text, exc.ToString());

            Coroutine.Execute(Show.MessageBox("An error occurred, and is copied to your clipboard:\n\n" + exc.Message, "Aww, Snap!"));
        }
    }
}
